//
//  MHListItemViewController.m
//  MHO
//
//  Created by papo on 2/22/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHListItemViewController.h"
#import "Lib.h"
#import "Contants.h"
#import "Application.h"
#import "MHGameCell.h"
#import "UIImageView+WebCache.h"
#import "MHGameHotSlider.h"
#import "MHGameDetailViewController.h"

@interface MHListItemViewController ()
@property (nonatomic, strong) MHGameHotSlider* slider;
@property (nonatomic, assign) int       currentPage;


@end

@implementation MHListItemViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.isShowHot = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.currentPage = 0;
    self.platform = 2;
    self.navibarView = [MHNavibarView createWithTitle:nil leftButton:nil rightButton:nil searchButton:NO];
    [self.navibarView setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:@selector(rightButtonPressed:) search:nil];
    [self.navibarView setRootViewController:self];
    [self.view addSubview:self.navibarView];

    [self reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [self refresh];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)leftButtonPressed:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonPressed:(id)sender  {

}


- (void)refresh {
    [self.data removeAllObjects];
    self.data = nil;
    [self reloadData];
}

- (void)loadingMore {
    [self loadMore];
}


- (void)reloadData {
    if (self.data) {
        return;
    }
    [Lib showLoadingView];
    [self LoadDataFromIndex:0];
}

- (void)loadMore {
    [self LoadDataFromIndex:self.currentPage];
}

- (void)LoadDataFromIndex:(int)pageIndex {
    self.isLoading = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* url = [Contants gameUrlWithCategory:_category idSystem:_platform idGroup:_group isHot:_hot isNew:_isNew mostView:_mostView pageIndex:pageIndex pageSize:10 key:kServerKey];
        if (self.listUrl) {
            url = [NSString stringWithFormat:self.listUrl, pageIndex, 10];
        }
        NSArray* array = [Application appsFromServiceUrl:url];
        NSLog(@"url: %@", url);
        
        if (pageIndex == 0 || !self.data) {
            self.data = [NSMutableArray arrayWithArray:array];
            if (self.isShowHot) {
                self.hotData = [NSMutableArray arrayWithArray:[Application getGameHot]];
            }
        }
        else {
            for (id game in array) {
                [self.data addObject:game];
            }
        }
        
        if (array.count > 0) {
            NSLog(@"array count: %lu", (unsigned long)array.count);
            self.currentPage = pageIndex + 1;;
        }
        
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoadingMore];
            [self stopLoading];
            [self.tableView reloadData];
        });
    });
}


#pragma mark - TableViewSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.data.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* CellIndentifier = @"Cell";
    if (indexPath.section == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            self.slider = [MHGameHotSlider sliderFromNib];
            
            NSMutableArray* viewsArray = [[NSMutableArray alloc] init];
            for (Application* app in self.hotData) {
                [viewsArray addObject:[Contants getImageUrl:app.imagePath width:320 height:120]];
            }
            [self.slider.infiSlider setViewsArray:viewsArray];
            [cell.contentView addSubview:self.slider];
        }
        [self.slider removeFromSuperview];
        [cell addSubview:self.slider];

        self.slider.hidden = !self.isShowHot;
        
        return cell;
    }
    else {

        MHGameCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [MHGameCell cellFromNib];
        }
        // configure cell
        Application* app = [self.data objectAtIndex:indexPath.row];
        if (app) {
            [cell setApp:app];
        }
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (!self.isShowHot) {
            return 0;
        }
        return 130;
    }
    
    return 85;
}


#pragma mark - UITabelView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        MHGameDetailViewController* vc = [[MHGameDetailViewController alloc] initWithNibName:@"MHGameDetailViewController" bundle:nil];
        Application* app = [self.data objectAtIndex:indexPath.row];
        vc.appId = app.appId.integerValue;
        vc.app = app;
        [self.navigationController pushViewController:vc animated:YES];
    }
}



@end
